// 数据服务层 - 负责处理数据的存储和检索
import { Student, Teacher, Class, Grade, Attendance, AuditLog, User, Dormitory, StageLevel, AcademyType } from './models';

// 数据存储接口
interface Storage<T> {
  getItems: () => Promise<T[]>;
  getItem: (id: string) => Promise<T | undefined>;
  setItem: (item: T) => Promise<void>;
  updateItem: (id: string, updates: Partial<T>) => Promise<void>;
  deleteItem: (id: string) => Promise<void>;
}

// 基于localStorage的持久化数据存储实现
class LocalStorage<T extends { id: string }> implements Storage<T> {
  private storageKey: string;

  constructor(storageKey: string) {
    this.storageKey = storageKey;
    // 初始化存储，如果不存在则创建空数组
    if (!localStorage.getItem(this.storageKey)) {
      localStorage.setItem(this.storageKey, JSON.stringify([]));
    }
  }

  async getItems(): Promise<T[]> {
    try {
      const itemsJson = localStorage.getItem(this.storageKey);
      if (!itemsJson) return [];
      return JSON.parse(itemsJson);
    } catch (error) {
      console.error(`Error loading items from localStorage (${this.storageKey}):`, error);
      return [];
    }
  }

  async getItem(id: string): Promise<T | undefined> {
    try {
      const items = await this.getItems();
      return items.find(item => item.id === id);
    } catch (error) {
      console.error(`Error getting item ${id} from localStorage (${this.storageKey}):`, error);
      return undefined;
    }
  }

  async setItem(item: T): Promise<void> {
    try {
      const items = await this.getItems();
      const existingIndex = items.findIndex(i => i.id === item.id);
      
      if (existingIndex !== -1) {
        // 更新现有项
        items[existingIndex] = item;
      } else {
        // 添加新项
        items.push(item);
      }
      
      localStorage.setItem(this.storageKey, JSON.stringify(items));
    } catch (error) {
      console.error(`Error saving item to localStorage (${this.storageKey}):`, error);
      throw error;
    }
  }

  async updateItem(id: string, updates: Partial<T>): Promise<void> {
    try {
      const items = await this.getItems();
      const index = items.findIndex(item => item.id === id);
      
      if (index !== -1) {
        items[index] = { ...items[index], ...updates };
        localStorage.setItem(this.storageKey, JSON.stringify(items));
      } else {
        throw new Error(`Item with id ${id} not found`);
      }
    } catch (error) {
      console.error(`Error updating item ${id} in localStorage (${this.storageKey}):`, error);
      throw error;
    }
  }

  async deleteItem(id: string): Promise<void> {
    try {
      const items = await this.getItems();
      const filteredItems = items.filter(item => item.id !== id);
      localStorage.setItem(this.storageKey, JSON.stringify(filteredItems));
    } catch (error) {
      console.error(`Error deleting item ${id} from localStorage (${this.storageKey}):`, error);
      throw error;
    }
  }
}

// 变更订阅回调类型
type ChangeCallback = (entityType: string, changeType: string, entityId: string) => void;

// 数据服务类 - 提供数据访问和操作的核心方法
export class DataService {
  // 数据存储实例
  private studentStorage: Storage<Student> = new LocalStorage<Student>('studentStorage');
  private teacherStorage: Storage<Teacher> = new LocalStorage<Teacher>('teacherStorage');
  private classStorage: Storage<Class> = new LocalStorage<Class>('classStorage');
  private gradeStorage: Storage<Grade> = new LocalStorage<Grade>('gradeStorage');
  private attendanceStorage: Storage<Attendance> = new LocalStorage<Attendance>('attendanceStorage');
  private auditLogStorage: Storage<AuditLog> = new LocalStorage<AuditLog>('auditLogStorage');
  
  // 初始化标志
  private initialized = false;
  
  // 变更订阅
  private changeSubscribers: ChangeCallback[] = [];

  // 生成唯一ID
  private generateId(): string {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
  }

  // 获取当前时间
  private getCurrentTime(): string {
    return new Date().toISOString();
  }

  // 触发数据变更通知
  private notifyChange(entityType: string, changeType: string, entityId: string): void {
    for (const callback of this.changeSubscribers) {
      try {
        callback(entityType, changeType, entityId);
      } catch (error) {
        console.error('Error in change subscriber:', error);
      }
    }
  }
  
  // 初始化宿舍数据的辅助方法
  private async initializeDormitoryData(): Promise<void> {
    // 强制清除现有宿舍数据，确保使用最新的宿舍数据
    console.log('强制清除现有宿舍数据，确保使用最新的宿舍数据');
    
    // 清除所有学生的宿舍关联
    const students = await this.getStudents();
    for (const student of students) {
      if (student.dormitoryId) {
        await this.updateStudent(student.id, { dormitoryId: undefined });
      }
    }
    
    // 清除所有现有宿舍数据
    const existingDormitories = await this.getDormitories();
    for (const dorm of existingDormitories) {
      await this.dormitoryStorage.deleteItem(dorm.id);
    }
    
    // 创建新的宿舍数据
    const dormitories: Dormitory[] = [];
    const currentTime = this.getCurrentTime();
    let dormIdCounter = 1;
    
    // 1. 学四舍（女生宿舍）
    const xuesisheFloors = [
      { floor: 1, notes: '新生宿舍' },
      { floor: 2, notes: '元宇宙女生宿舍' },
      { floor: 3, notes: '鸿蒙生态开发女生宿舍' },
      { floor: 4, notes: '云计算女生宿舍' },
      { floor: 5, notes: '数智传媒女生宿舍' },
      { floor: 6, notes: '人工智能女生宿舍' }
    ];
    
    for (const floorInfo of xuesisheFloors) {
      for (let roomNum = 1; roomNum <= 10; roomNum++) {
        const roomNumber = `${floorInfo.floor}${roomNum.toString().padStart(2, '0')}`;
        dormitories.push({
          id: `dorm-${dormIdCounter++}`,
          building: '学四舍',
          roomNumber: roomNumber,
          type: 'female',
          capacity: 8,
          currentOccupancy: 0,
          students: [],
          floor: floorInfo.floor,
          status: 'active',
          notes: floorInfo.notes,
          createdAt: currentTime,
          updatedAt: currentTime
        });
      }
    }
    
    // 2. 学三舍（元宇宙男生宿舍和鸿蒙生态开发男生宿舍）
    // 假设元宇宙在1-3层，鸿蒙生态开发在4-6层
    for (let floor = 1; floor <= 6; floor++) {
      const notes = floor <= 3 ? '元宇宙男生宿舍' : '鸿蒙生态开发男生宿舍';
      for (let roomNum = 1; roomNum <= 10; roomNum++) {
        const roomNumber = `${floor}${roomNum.toString().padStart(2, '0')}`;
        dormitories.push({
          id: `dorm-${dormIdCounter++}`,
          building: '学三舍',
          roomNumber: roomNumber,
          type: 'male',
          capacity: 8,
          currentOccupancy: 0,
          students: [],
          floor: floor,
          status: 'active',
          notes: notes,
          createdAt: currentTime,
          updatedAt: currentTime
        });
      }
    }
    
    // 3. 皇悦三期（人工智能和云计算男生宿舍）
    // 假设人工智能在1-3层，云计算在4-6层
    for (let floor = 1; floor <= 6; floor++) {
      const notes = floor <= 3 ? '人工智能男生宿舍' : '云计算男生宿舍';
      for (let roomNum = 1; roomNum <= 5; roomNum++) {
        const roomNumber = `93${floor}${roomNum.toString().padStart(2, '0')}`;
        dormitories.push({
          id: `dorm-${dormIdCounter++}`,
          building: '皇悦三期',
          roomNumber: roomNumber,
          type: 'male',
          capacity: 8,
          currentOccupancy: 0,
          students: [],
          floor: floor,
          status: 'active',
          notes: notes,
          createdAt: currentTime,
          updatedAt: currentTime
        });
      }
    }
    
    // 4. 皇悦一期（数智传媒男生宿舍）
    for (let floor = 1; floor <= 6; floor++) {
      for (let roomNum = 1; roomNum <= 10; roomNum++) {
        const roomNumber = `91${floor}${roomNum.toString().padStart(2, '0')}`;
        dormitories.push({
          id: `dorm-${dormIdCounter++}`,
          building: '皇悦一期',
          roomNumber: roomNumber,
          type: 'male',
          capacity: 8,
          currentOccupancy: 0,
          students: [],
          floor: floor,
          status: 'active',
          notes: '数智传媒男生宿舍',
          createdAt: currentTime,
          updatedAt: currentTime
        });
      }
    }
    
    // 保存所有宿舍数据
    for (const dorm of dormitories) {
      await this.dormitoryStorage.setItem(dorm);
    }
    
    console.log(`宿舍数据初始化完成，共创建 ${dormitories.length} 间宿舍`);
  }

  // 订阅数据变更
  subscribeToChanges(callback: ChangeCallback): () => void {
    this.changeSubscribers.push(callback);
    return () => {
      this.changeSubscribers = this.changeSubscribers.filter(cb => cb !== callback);
    };
  }

  // 记录操作日志
  private async logOperation(action: string, entityType: string, entityId: string, user?: User): Promise<void> {
    const log: AuditLog = {
      id: this.generateId(),
      action,
      entityType,
      entityId,
      timestamp: this.getCurrentTime(),
      userId: user?.id,
      userName: user?.name || 'System'
    };
    await this.auditLogStorage.setItem(log);
  }

  // 更新班级学生数量
  private async updateClassStudentCount(classId: string): Promise<void> {
    const students = await this.studentStorage.getItems();
    // 只计算激活状态的学生
    const activeStudentsInClass = students.filter(
      student => student.classId === classId && student.status === 'active'
    );
    
    await this.classStorage.updateItem(classId, {
      studentCount: activeStudentsInClass.length
    });
  }
  
  // 更新宿舍入住人数
  private async updateDormitoryOccupancy(dormitoryId: string): Promise<void> {
    try {
      // 首先检查宿舍是否存在
      const dormitories = await this.dormitoryStorage.getItems();
      const dormitoryExists = dormitories.some(dorm => dorm.id === dormitoryId);
      
      if (!dormitoryExists) {
        console.warn(`跳过更新不存在的宿舍: ${dormitoryId}`);
        return;
      }
      
      const students = await this.studentStorage.getItems();
      // 计算入住该宿舍的学生数量
      const studentsInDormitory = students.filter(
        student => student.dormitoryId === dormitoryId && student.status === 'active'
      );
      
      await this.dormitoryStorage.updateItem(dormitoryId, {
        currentOccupancy: studentsInDormitory.length,
        students: studentsInDormitory.map(student => student.id)
      });
    } catch (error) {
      console.error(`更新宿舍入住状态失败 (${dormitoryId}):`, error);
      // 不抛出错误，避免初始化过程中断
    }
  }

  // 初始化模拟数据
  private async initData(): Promise<void> {
    console.log('Starting DataService initialization');
    
    // 检查是否已经初始化过
    if (this.initialized) {
      console.log('Data already initialized, skipping initialization');
      return;
    }
    
    // 重置initialized标志
    this.initialized = false;
    
    console.log('Initializing all data to localStorage');
    
    // 初始化班级数据 - 每个学院都包含全部26个班级，保持班级名称简洁
    const academies = ['人工智能', '数智传媒', '鸿蒙生态开发', '云计算', '元宇宙', '市场部', '专业二'];

    const baseClasses = [
      // 专业一：2509A - 专业阶段
      { name: '2509A', stage: '专业阶段', advisorId: 'teacher-1', advisorName: '张导员', lecturerId: 'lecturer-1', lecturerName: '张讲师', studentCount: 3, subjects: ['chinese', 'math', 'english'], status: 'active' },
      // 专业二：2508A、2508B - 专业阶段
      { name: '2508A', stage: '专业阶段', advisorId: 'teacher-2', advisorName: '王导员', lecturerId: 'lecturer-2', lecturerName: '王讲师', studentCount: 4, subjects: ['chinese', 'math', 'english'], status: 'active' },
      { name: '2508B', stage: '专业阶段', advisorId: 'teacher-2', advisorName: '王导员', lecturerId: 'lecturer-2', lecturerName: '王讲师', studentCount: 3, subjects: ['chinese', 'math', 'english'], status: 'active' },
      // 专业三：2507A、2507B - 专业阶段
      { name: '2507A', stage: '专业阶段', advisorId: 'teacher-3', advisorName: '李导员', lecturerId: 'lecturer-3', lecturerName: '李讲师', studentCount: 5, subjects: ['chinese', 'math', 'english'], status: 'active' },
      { name: '2507B', stage: '专业阶段', advisorId: 'teacher-3', advisorName: '李导员', lecturerId: 'lecturer-3', lecturerName: '李讲师', studentCount: 4, subjects: ['chinese', 'math', 'english'], status: 'active' },
      // 专业四：2506A - 专业阶段
      { name: '2506A', stage: '专业阶段', advisorId: 'teacher-4', advisorName: '赵导员', lecturerId: 'lecturer-4', lecturerName: '赵讲师', studentCount: 6, subjects: ['chinese', 'math', 'english'], status: 'active' },
      // 专业五：2505A - 专业阶段
      { name: '2505A', stage: '专业阶段', advisorId: 'teacher-5', advisorName: '刘导员', lecturerId: 'lecturer-5', lecturerName: '刘讲师', studentCount: 3, subjects: ['chinese', 'math', 'english'], status: 'active' },
      // 专高一：2504A - 专高阶段
      { name: '2504A', stage: '专高阶段', advisorId: 'teacher-6', advisorName: '陈导员', lecturerId: 'lecturer-6', lecturerName: '陈讲师', studentCount: 5, subjects: ['chinese', 'math', 'english'], status: 'active' },
      // 专高二：2503A - 专高阶段
      { name: '2503A', stage: '专高阶段', advisorId: 'teacher-7', advisorName: '杨导员', lecturerId: 'lecturer-7', lecturerName: '杨讲师', studentCount: 4, subjects: ['chinese', 'math', 'english'], status: 'active' },
      // 专高三：2502A、2502C - 专高阶段
      { name: '2502A', stage: '专高阶段', advisorId: 'teacher-8', advisorName: '黄导员', lecturerId: 'lecturer-8', lecturerName: '黄讲师', studentCount: 6, subjects: ['chinese', 'math', 'english'], status: 'active' },
      { name: '2502C', stage: '专高阶段', advisorId: 'teacher-8', advisorName: '黄导员', lecturerId: 'lecturer-8', lecturerName: '黄讲师', studentCount: 3, subjects: ['chinese', 'math', 'english'], status: 'active' },
      // 专高四：2501A - 专高阶段
      { name: '2501A', stage: '专高阶段', advisorId: 'teacher-1', advisorName: '张导员', lecturerId: 'lecturer-1', lecturerName: '张讲师', studentCount: 5, subjects: ['chinese', 'math', 'english'], status: 'active' },
      // 专高五：2412A、2412C - 专高阶段
      { name: '2412A', stage: '专高阶段', advisorId: 'teacher-2', advisorName: '王导员', lecturerId: 'lecturer-2', lecturerName: '王讲师', studentCount: 4, subjects: ['chinese', 'math', 'english'], status: 'active' },
      { name: '2412C', stage: '专高阶段', advisorId: 'teacher-2', advisorName: '王导员', lecturerId: 'lecturer-2', lecturerName: '王讲师', studentCount: 3, subjects: ['chinese', 'math', 'english'], status: 'active' },
      // 专高六：2411A、2411B、2411C - 专高阶段
      { name: '2411A', stage: '专高阶段', advisorId: 'teacher-3', advisorName: '李导员', lecturerId: 'lecturer-3', lecturerName: '李讲师', studentCount: 6, subjects: ['chinese', 'math', 'english'], status: 'active' },
      { name: '2411B', stage: '专高阶段', advisorId: 'teacher-3', advisorName: '李导员', lecturerId: 'lecturer-3', lecturerName: '李讲师', studentCount: 4, subjects: ['chinese', 'math', 'english'], status: 'active' },
      { name: '2411C', stage: '专高阶段', advisorId: 'teacher-3', advisorName: '李导员', lecturerId: 'lecturer-3', lecturerName: '李讲师', studentCount: 3, subjects: ['chinese', 'math', 'english'], status: 'active' },
      // 实训一：2410A、2410B、2410C、2410D - 实训阶段
      { name: '2410A', stage: '实训阶段', advisorId: 'teacher-4', advisorName: '赵导员', lecturerId: 'lecturer-4', lecturerName: '赵讲师', studentCount: 5, subjects: ['chinese', 'math', 'english'], status: 'active' },
      { name: '2410B', stage: '实训阶段', advisorId: 'teacher-4', advisorName: '赵导员', lecturerId: 'lecturer-4', lecturerName: '赵讲师', studentCount: 4, subjects: ['chinese', 'math', 'english'], status: 'active' },
      { name: '2410C', stage: '实训阶段', advisorId: 'teacher-4', advisorName: '赵导员', lecturerId: 'lecturer-4', lecturerName: '赵讲师', studentCount: 3, subjects: ['chinese', 'math', 'english'], status: 'active' },
      { name: '2410D', stage: '实训阶段', advisorId: 'teacher-4', advisorName: '赵导员', lecturerId: 'lecturer-4', lecturerName: '赵讲师', studentCount: 2, subjects: ['chinese', 'math', 'english'], status: 'active' },
      // 实训二：2409A、2409B、2409C - 实训阶段
      { name: '2409A', stage: '实训阶段', advisorId: 'teacher-5', advisorName: '刘导员', lecturerId: 'lecturer-5', lecturerName: '刘讲师', studentCount: 5, subjects: ['chinese', 'math', 'english'], status: 'active' },
      { name: '2409B', stage: '实训阶段', advisorId: 'teacher-5', advisorName: '刘导员', lecturerId: 'lecturer-5', lecturerName: '刘讲师', studentCount: 4, subjects: ['chinese', 'math', 'english'], status: 'active' },
      { name: '2409C', stage: '实训阶段', advisorId: 'teacher-5', advisorName: '刘导员', lecturerId: 'lecturer-5', lecturerName: '刘讲师', studentCount: 3, subjects: ['chinese', 'math', 'english'], status: 'active' },
      // 实训三：2408A、2408B - 实训阶段
      { name: '2408A', stage: '实训阶段', advisorId: 'teacher-6', advisorName: '陈导员', lecturerId: 'lecturer-6', lecturerName: '陈讲师', studentCount: 4, subjects: ['chinese', 'math', 'english'], status: 'active' },
      { name: '2408B', stage: '实训阶段', advisorId: 'teacher-6', advisorName: '陈导员', lecturerId: 'lecturer-6', lecturerName: '陈讲师', studentCount: 3, subjects: ['chinese', 'math', 'english'], status: 'active' }
    ];

    // 为每个学院生成所有班级
    let idCounter = 1;
    const classes = [];
    
    academies.forEach(academy => {
      baseClasses.forEach(baseClass => {
        classes.push({
          id: idCounter.toString(),
          ...baseClass,
          academy,
          createdAt: this.getCurrentTime(),
          updatedAt: this.getCurrentTime()
        });
        idCounter++;
      });
    });
    
    // 保存班级数据
    for (const cls of classes) {
      await this.classStorage.setItem(cls as Class);
    }
    
    // 初始化教师数据
    const teachers = [
      // 导员数据
      { id: 'teacher-1', name: '张导员', email: 'zhang@example.com', phone: '13800138001', role: 'instructor', status: 'active', createdAt: this.getCurrentTime(), updatedAt: this.getCurrentTime() },
      { id: 'teacher-2', name: '王导员', email: 'wang@example.com', phone: '13800138002', role: 'instructor', status: 'active', createdAt: this.getCurrentTime(), updatedAt: this.getCurrentTime() },
      { id: 'teacher-3', name: '李导员', email: 'li@example.com', phone: '13800138003', role: 'instructor', status: 'active', createdAt: this.getCurrentTime(), updatedAt: this.getCurrentTime() },
      { id: 'teacher-4', name: '赵导员', email: 'zhao@example.com', phone: '13800138004', role: 'instructor', status: 'active', createdAt: this.getCurrentTime(), updatedAt: this.getCurrentTime() },
      { id: 'teacher-5', name: '刘导员', email: 'liu@example.com', phone: '13800138005', role: 'instructor', status: 'active', createdAt: this.getCurrentTime(), updatedAt: this.getCurrentTime() },
      { id: 'teacher-6', name: '陈导员', email: 'chen@example.com', phone: '13800138006', role: 'instructor', status: 'active', createdAt: this.getCurrentTime(), updatedAt: this.getCurrentTime() },
      { id: 'teacher-7', name: '杨导员', email: 'yang@example.com', phone: '13800138007', role: 'instructor', status: 'active', createdAt: this.getCurrentTime(), updatedAt: this.getCurrentTime() },
      { id: 'teacher-8', name: '黄导员', email: 'huang@example.com', phone: '13800138008', role: 'instructor', status: 'active', createdAt: this.getCurrentTime(), updatedAt: this.getCurrentTime() },
      
      // 讲师数据
      { id: 'lecturer-1', name: '张讲师', email: 'zhang_lecturer@example.com', phone: '13900139001', role: 'lecturer', status: 'active', createdAt: this.getCurrentTime(), updatedAt: this.getCurrentTime() },
      { id: 'lecturer-2', name: '王讲师', email: 'wang_lecturer@example.com', phone: '13900139002', role: 'lecturer', status: 'active', createdAt: this.getCurrentTime(), updatedAt: this.getCurrentTime() },
      { id: 'lecturer-3', name: '李讲师', email: 'li_lecturer@example.com', phone: '13900139003', role: 'lecturer', status: 'active', createdAt: this.getCurrentTime(), updatedAt: this.getCurrentTime() },
      { id: 'lecturer-4', name: '赵讲师', email: 'zhao_lecturer@example.com', phone: '13900139004', role: 'lecturer', status: 'active', createdAt: this.getCurrentTime(), updatedAt: this.getCurrentTime() },
      { id: 'lecturer-5', name: '刘讲师', email: 'liu_lecturer@example.com', phone: '13900139005', role: 'lecturer', status: 'active', createdAt: this.getCurrentTime(), updatedAt: this.getCurrentTime() },
      { id: 'lecturer-6', name: '陈讲师', email: 'chen_lecturer@example.com', phone: '13900139006', role: 'lecturer', status: 'active', createdAt: this.getCurrentTime(), updatedAt: this.getCurrentTime() },
      { id: 'lecturer-7', name: '杨讲师', email: 'yang_lecturer@example.com', phone: '13900139007', role: 'lecturer', status: 'active', createdAt: this.getCurrentTime(), updatedAt: this.getCurrentTime() },
      { id: 'lecturer-8', name: '黄讲师', email: 'huang_lecturer@example.com', phone: '13900139008', role: 'lecturer', status: 'active', createdAt: this.getCurrentTime(), updatedAt: this.getCurrentTime() }
    ];
    
    // 保存教师数据
    for (const teacher of teachers) {
      await this.teacherStorage.setItem(teacher as Teacher);
    }
    
    // 初始化完成，设置标志
    this.initialized = true;
    console.log('Data initialization completed successfully');
    
    // 初始化学生数据
    const studentStatuses = ['active', 'suspended', 'transferred', 'graduated'];
    const studentNames = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十', '郑十一', '王十二', '陈十三', '杨十四', '黄十五', '刘十六', '周十七', '吴十八', '郑十九', '李二十', '张二十一', '王二十二'];
    
    let studentCounter = 1;
    
    // 预先定义宿舍分配映射
    const dormitoryAssignment = {
      // 为每个学院和性别组合创建计数器
      female: {
        '元宇宙': { building: '学四舍', floor: 2, currentRoom: 1, currentBed: 1 },
        '鸿蒙生态开发': { building: '学四舍', floor: 3, currentRoom: 1, currentBed: 1 },
        '云计算': { building: '学四舍', floor: 4, currentRoom: 1, currentBed: 1 },
        '数智传媒': { building: '学四舍', floor: 5, currentRoom: 1, currentBed: 1 },
        '人工智能': { building: '学四舍', floor: 6, currentRoom: 1, currentBed: 1 },
        'default': { building: '学四舍', floor: 1, currentRoom: 1, currentBed: 1 } // 新生宿舍
      },
      male: {
        '元宇宙': { building: '学三舍', floor: 1, currentRoom: 1, currentBed: 1 },
        '鸿蒙生态开发': { building: '学三舍', floor: 4, currentRoom: 1, currentBed: 1 },
        '人工智能': { building: '皇悦三期', floor: 1, currentRoom: 1, currentBed: 1 },
        '云计算': { building: '皇悦三期', floor: 4, currentRoom: 1, currentBed: 1 },
        '数智传媒': { building: '皇悦一期', floor: 1, currentRoom: 1, currentBed: 1 }
      }
    };

    // 首先初始化宿舍数据，确保宿舍存在
    await this.initializeDormitoryData();
    
    // 然后初始化学生数据并分配宿舍
    for (const cls of classes) {
      for (let i = 0; i < cls.studentCount; i++) {
        // 确保生成的名字不重复
        let nameIndex = (studentCounter - 1) % studentNames.length;
        let name = studentNames[nameIndex];
        if (studentCounter > studentNames.length) {
          name += Math.ceil(studentCounter / studentNames.length);
        }
        
        const gender = Math.random() > 0.5 ? 'male' : 'female';
        const academy = ['人工智能', '数智传媒', '鸿蒙生态开发', '云计算', '元宇宙'][Math.floor(Math.random() * 5)] as AcademyType;
        
        // 根据性别和学院分配宿舍
        let dormitoryId = undefined;
        
        if (gender === 'female') {
          // 女生统一分配到学四舍
          const academyAssignment = dormitoryAssignment.female[academy] || dormitoryAssignment.female.default;
          
          // 计算宿舍ID（假设宿舍ID是按顺序生成的，需要与initializeDormitoryData方法中的ID生成逻辑对应）
          // 学四舍：dorm-1 到 dorm-60（6层，每层10间）
          const baseIdForXuesishe = 0; // 学四舍从dorm-1开始
          const floorOffset = (academyAssignment.floor - 1) * 10;
          const roomOffset = academyAssignment.currentRoom - 1;
          dormitoryId = `dorm-${baseIdForXuesishe + floorOffset + roomOffset + 1}`;
          
          // 更新床位计数器
          academyAssignment.currentBed++;
          if (academyAssignment.currentBed > 8) { // 每间宿舍8个床位
            academyAssignment.currentBed = 1;
            academyAssignment.currentRoom++;
            // 如果当前楼层房间用完，移到下一层
            if (academyAssignment.currentRoom > 10) {
              academyAssignment.currentRoom = 1;
              // 学四舍只有6层
              if (academyAssignment.floor < 6) {
                academyAssignment.floor++;
              }
            }
          }
        } else if (gender === 'male') {
          // 男生根据学院分配到不同宿舍楼
          const academyAssignment = dormitoryAssignment.male[academy];
          
          let baseId = 0;
          let roomsPerFloor = 10;
          
          if (academyAssignment.building === '学三舍') {
            // 学三舍：dorm-61 到 dorm-120（6层，每层10间）
            baseId = 60;
          } else if (academyAssignment.building === '皇悦三期') {
            // 皇悦三期：dorm-121 到 dorm-150（6层，每层5间）
            baseId = 120;
            roomsPerFloor = 5;
          } else if (academyAssignment.building === '皇悦一期') {
            // 皇悦一期：dorm-151 到 dorm-210（6层，每层10间）
            baseId = 150;
          }
          
          const floorOffset = (academyAssignment.floor - 1) * roomsPerFloor;
          const roomOffset = academyAssignment.currentRoom - 1;
          dormitoryId = `dorm-${baseId + floorOffset + roomOffset + 1}`;
          
          // 更新床位计数器
          academyAssignment.currentBed++;
          if (academyAssignment.currentBed > 8) { // 每间宿舍8个床位
            academyAssignment.currentBed = 1;
            academyAssignment.currentRoom++;
            // 如果当前楼层房间用完，移到下一层
            if (academyAssignment.currentRoom > roomsPerFloor) {
              academyAssignment.currentRoom = 1;
              // 每个男生宿舍区都有6层，但根据学院分配在不同楼层范围
              if (academy === '元宇宙' && academyAssignment.floor < 3) {
                academyAssignment.floor++;
              } else if (academy === '鸿蒙生态开发' && academyAssignment.floor < 6) {
                academyAssignment.floor++;
              } else if (academy === '人工智能' && academyAssignment.floor < 3) {
                academyAssignment.floor++;
              } else if (academy === '云计算' && academyAssignment.floor < 6) {
                academyAssignment.floor++;
              } else if (academy === '数智传媒' && academyAssignment.floor < 6) {
                academyAssignment.floor++;
              }
            }
          }
        }
        
        const student: Student = {
          id: `student-${studentCounter.toString().padStart(4, '0')}`,
          name: name,
          studentId: `S${2023}${studentCounter.toString().padStart(4, '0')}`,
          gender: gender,
          dateOfBirth: new Date(Date.now() - Math.random() * 1000 * 60 * 60 * 24 * 365 * 18).toISOString().split('T')[0],
          admissionDate: new Date(Date.now() - Math.random() * 1000 * 60 * 60 * 24 * 365).toISOString().split('T')[0],
          classId: cls.id,
          stage: cls.stage as 'freshman' | 'sophomore' | 'junior',
          academy: academy,
          phoneNumber: `13${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}${Math.floor(Math.random() * 10)}`,
          email: `student${studentCounter}@example.com`,
          address: `中国某某省某某市某某区某某路${Math.floor(Math.random() * 100)}号`,
          dormitoryId: dormitoryId,
          status: 'active', // 确保初始状态都是active，这样updateClassStudentCount会正确计算
          createdAt: this.getCurrentTime(),
          updatedAt: this.getCurrentTime()
        };
        
        await this.studentStorage.setItem(student);
        
        // 创建学生后更新宿舍入住人数
        if (dormitoryId) {
          await this.updateDormitoryOccupancy(dormitoryId);
        }
        
        studentCounter++;
      }
    }
    
    // 初始化成绩数据 - 按照用户要求格式
    const term = '2025.9.22-2025.10.24'; // 固定的一个月教学周期
    const examTypes = ['周考', '月考']; // 只使用这两种考试类型
    
    // 阶段到教学月度的映射
    const stageToTeachingMonth = {
      '专业阶段': 'zhuangao1',
      '专高阶段': 'zhuangao6', // 专高六
      '实训阶段': 'shixun1'
    };
    
    // 为每个班级创建成绩记录
    for (const cls of classes) {
      // 根据班级阶段获取对应的教学月度
      const teachingMonth = stageToTeachingMonth[cls.stage] || 'zhuangao1';
      
      // 为每个班级创建周考和月考两条记录
      for (const examType of examTypes) {
        // 创建成绩记录，课程先留空
        const gradeRecord: Grade = {
          id: `grade-${this.generateId()}`,
          term: term,
          examType: examType,
          studentId: '', // 可以为空
          studentName: '', // 可以为空
          subject: '', // 按要求先空着
          score: 0,
          academy: cls.academy,
          className: cls.name,
          instructor: cls.advisorName || '',
          instructorId: cls.advisorId || '',
          lecturer: cls.lecturerName || '',
          lecturerId: cls.lecturerId || '',
          teachingMonth: teachingMonth,
          totalStudents: cls.studentCount,
          createdAt: this.getCurrentTime(),
          updatedAt: this.getCurrentTime()
        };
        
        await this.gradeStorage.setItem(gradeRecord);
      }
    }
    
    // 所有数据初始化完成后设置初始化标志
    this.initialized = true;
  }

  // 学生相关方法
  async getStudents(): Promise<Student[]> {
    // 确保数据已初始化
    await this.initData();
    return this.studentStorage.getItems();
  }

  async getStudentById(id: string): Promise<Student | undefined> {
    return this.studentStorage.getItem(id);
  }

  async createStudent(student: Omit<Student, 'id' | 'createdAt' | 'updatedAt'>): Promise<Student> {
    const newStudent: Student = {
      ...student,
      id: this.generateId(),
      createdAt: this.getCurrentTime(),
      updatedAt: this.getCurrentTime()
    };
    await this.studentStorage.setItem(newStudent);
    await this.updateClassStudentCount(newStudent.classId);
    // 如果学生分配了宿舍，更新宿舍入住人数
    if (newStudent.dormitoryId) {
      await this.updateDormitoryOccupancy(newStudent.dormitoryId);
    }
    await this.logOperation('create', 'student', newStudent.id);
    this.notifyChange('student', 'create', newStudent.id);
    return newStudent;
  }

  async updateStudent(id: string, updates: Partial<Student>): Promise<void> {
    const student = await this.getStudentById(id);
    if (!student) throw new Error('Student not found');
    
    const oldClassId = student.classId;
    const needsClassUpdate = updates.classId && updates.classId !== oldClassId;
    
    const oldDormitoryId = student.dormitoryId;
    const needsDormitoryUpdate = updates.dormitoryId !== undefined && updates.dormitoryId !== oldDormitoryId;
    
    // 检查学生状态是否变更（active状态会影响宿舍入住人数计算）
    const oldStatus = student.status;
    const newStatus = updates.status || oldStatus;
    const statusChanged = oldStatus !== newStatus;
    const statusAffectsOccupancy = (oldStatus === 'active' || newStatus === 'active') && oldDormitoryId;
    
    await this.studentStorage.updateItem(id, {
      ...updates,
      updatedAt: this.getCurrentTime()
    });
    
    // 如果学生换班，更新两个班级的学生数量
    await this.updateClassStudentCount(oldClassId);
    if (needsClassUpdate && updates.classId) {
      await this.updateClassStudentCount(updates.classId);
    }
    
    // 如果学生换宿舍或状态变更影响入住计算，更新相关宿舍的入住人数
    if (oldDormitoryId && (needsDormitoryUpdate || statusAffectsOccupancy)) {
      await this.updateDormitoryOccupancy(oldDormitoryId);
    }
    if (needsDormitoryUpdate && updates.dormitoryId) {
      await this.updateDormitoryOccupancy(updates.dormitoryId);
    }
    
    await this.logOperation('update', 'student', id);
    this.notifyChange('student', 'update', id);
  }

  async deleteStudent(id: string): Promise<void> {
    const student = await this.getStudentById(id);
    if (!student) throw new Error('Student not found');
    
    const classId = student.classId;
    const dormitoryId = student.dormitoryId;
    
    await this.studentStorage.deleteItem(id);
    await this.updateClassStudentCount(classId);
    // 如果学生分配了宿舍，更新宿舍入住人数
    if (dormitoryId) {
      await this.updateDormitoryOccupancy(dormitoryId);
    }
    await this.logOperation('delete', 'student', id);
    this.notifyChange('student', 'delete', id);
  }

  // 教师相关方法
  async getTeachers(): Promise<Teacher[]> {
    try {
      return await this.teacherStorage.getItems() || [];
    } catch (error) {
      console.warn('获取教师数据失败，返回空数组:', error);
      return [];
    }
  }

  async getTeacherById(id: string): Promise<Teacher | undefined> {
    return this.teacherStorage.getItem(id);
  }

  async createTeacher(teacher: Omit<Teacher, 'id' | 'createdAt' | 'updatedAt'>): Promise<Teacher> {
    const newTeacher: Teacher = {
      ...teacher,
      id: this.generateId(),
      createdAt: this.getCurrentTime(),
      updatedAt: this.getCurrentTime()
    };
    await this.teacherStorage.setItem(newTeacher);
    await this.logOperation('create', 'teacher', newTeacher.id);
    this.notifyChange('teacher', 'create', newTeacher.id);
    return newTeacher;
  }

  async updateTeacher(id: string, updates: Partial<Teacher>): Promise<void> {
    await this.teacherStorage.updateItem(id, {
      ...updates,
      updatedAt: this.getCurrentTime()
    });
    await this.logOperation('update', 'teacher', id);
    this.notifyChange('teacher', 'update', id);
  }

  async deleteTeacher(id: string): Promise<void> {
    await this.teacherStorage.deleteItem(id);
    await this.logOperation('delete', 'teacher', id);
    this.notifyChange('teacher', 'delete', id);
  }

  // 班级相关方法
  async getClasses(): Promise<Class[]> {
    // 确保数据已初始化
    await this.initData();
    return this.classStorage.getItems();
  }

  async getClassById(id: string): Promise<Class | undefined> {
    return this.classStorage.getItem(id);
  }

  async createClass(cls: Omit<Class, 'id' | 'createdAt' | 'updatedAt'>): Promise<Class> {
    const newClass: Class = {
      ...cls,
      id: this.generateId(),
      studentCount: 0, // 新班级默认学生数为0
      createdAt: this.getCurrentTime(),
      updatedAt: this.getCurrentTime()
    };
    await this.classStorage.setItem(newClass);
    await this.logOperation('create', 'class', newClass.id);
    this.notifyChange('class', 'create', newClass.id);
    return newClass;
  }

  async updateClass(id: string, updates: Partial<Class>): Promise<void> {
    await this.classStorage.updateItem(id, {
      ...updates,
      updatedAt: this.getCurrentTime()
    });
    await this.logOperation('update', 'class', id);
    this.notifyChange('class', 'update', id);
  }

  async deleteClass(id: string): Promise<void> {
    // 在删除班级前，需要更新所有关联学生的班级信息
    const students = await this.getStudents();
    for (const student of students) {
      if (student.classId === id) {
        await this.updateStudent(student.id, { classId: '' });
      }
    }
    
    await this.classStorage.deleteItem(id);
    await this.logOperation('delete', 'class', id);
    this.notifyChange('class', 'delete', id);
  }

  // 成绩相关方法
  async getGrades(): Promise<Grade[]> {
    return this.gradeStorage.getItems();
  }

  async getGradesByStudentId(studentId: string): Promise<Grade[]> {
    const grades = await this.getGrades();
    return grades.filter(grade => grade.studentId === studentId);
  }

  async createGrade(grade: Omit<Grade, 'id' | 'createdAt' | 'updatedAt'>): Promise<Grade> {
    const newGrade: Grade = {
      ...grade,
      id: this.generateId(),
      createdAt: this.getCurrentTime(),
      updatedAt: this.getCurrentTime()
    };
    await this.gradeStorage.setItem(newGrade);
    await this.logOperation('create', 'grade', newGrade.id);
    this.notifyChange('grade', 'create', newGrade.id);
    return newGrade;
  }

  // 考勤相关方法
  async getAttendances(): Promise<Attendance[]> {
    return this.attendanceStorage.getItems();
  }

  async getAttendancesByStudentId(studentId: string): Promise<Attendance[]> {
    const attendances = await this.getAttendances();
    return attendances.filter(attendance => attendance.studentId === studentId);
  }

  // 宿舍相关方法
  private dormitoryStorage: Storage<Dormitory> = new LocalStorage<Dormitory>('dormitoryStorage');
  
  async getDormitories(): Promise<Dormitory[]> {
    // 确保数据已初始化
    await this.initData();
    const dormitories = await this.dormitoryStorage.getItems();
    // 确保每个宿舍的学生列表都被初始化
    return dormitories.map(dorm => ({
      ...dorm,
      students: dorm.students || []
    }));
  }
  
  async getDormitoryById(id: string): Promise<Dormitory | null> {
    const dormitory = await this.dormitoryStorage.getItem(id);
    if (dormitory) {
      // 确保学生列表被初始化
      dormitory.students = dormitory.students || [];
    }
    return dormitory;
  }
  
  // 获取宿舍及其入住学生的详细信息
  async getDormitoryWithStudents(dormitoryId: string): Promise<(Dormitory & { studentDetails: Student[] }) | null> {
    const dormitory = await this.getDormitoryById(dormitoryId);
    if (!dormitory) return null;
    
    const studentDetails: Student[] = [];
    for (const studentId of dormitory.students) {
      const student = await this.getStudentById(studentId);
      if (student) {
        studentDetails.push(student);
      }
    }
    
    return {
      ...dormitory,
      studentDetails
    };
  }
  
  // 获取学生及其所在宿舍的详细信息
  async getStudentWithDormitory(studentId: string): Promise<(Student & { dormitoryDetails?: Dormitory }) | null> {
    const student = await this.getStudentById(studentId);
    if (!student) return null;
    
    if (student.dormitoryId) {
      const dormitory = await this.getDormitoryById(student.dormitoryId);
      return {
        ...student,
        dormitoryDetails: dormitory || undefined
      };
    }
    
    return {
      ...student,
      dormitoryDetails: undefined
    };
  }
  
  async createDormitory(dormitory: Omit<Dormitory, 'id' | 'createdAt' | 'updatedAt'>): Promise<Dormitory> {
    const newDormitory: Dormitory = {
      ...dormitory,
      id: this.generateId(),
      createdAt: this.getCurrentTime(),
      updatedAt: this.getCurrentTime()
    };
    await this.dormitoryStorage.setItem(newDormitory);
    await this.logOperation('create', 'dormitory', newDormitory.id);
    this.notifyChange('dormitory', 'create', newDormitory.id);
    return newDormitory;
  }
  
  async updateDormitory(id: string, updates: Partial<Dormitory>): Promise<void> {
    await this.dormitoryStorage.updateItem(id, {
      ...updates,
      updatedAt: this.getCurrentTime()
    });
    await this.logOperation('update', 'dormitory', id);
    this.notifyChange('dormitory', 'update', id);
  }
  
  async deleteDormitory(id: string): Promise<void> {
    // 在删除宿舍前，需要解除所有关联学生的宿舍信息
    const students = await this.getStudents();
    for (const student of students) {
      if (student.dormitoryId === id) {
        await this.updateStudent(student.id, { dormitoryId: undefined });
      }
    }
    
    await this.dormitoryStorage.deleteItem(id);
    await this.logOperation('delete', 'dormitory', id);
    this.notifyChange('dormitory', 'delete', id);
  }
  
  async getBuildings(): Promise<string[]> {
    const dormitories = await this.getDormitories();
    const buildings = [...new Set(dormitories.map(d => d.building))];
    return buildings;
  }

  async getAttendancesByClassId(classId: string): Promise<Attendance[]> {
    const attendances = await this.getAttendances();
    return attendances.filter(attendance => attendance.classId === classId);
  }

  async createAttendance(attendance: Omit<Attendance, 'id' | 'createdAt' | 'updatedAt'>): Promise<Attendance> {
    const newAttendance: Attendance = {
      ...attendance,
      id: this.generateId(),
      createdAt: this.getCurrentTime(),
      updatedAt: this.getCurrentTime()
    };
    await this.attendanceStorage.setItem(newAttendance);
    await this.logOperation('create', 'attendance', newAttendance.id);
    this.notifyChange('attendance', 'create', newAttendance.id);
    return newAttendance;
  }

  // 日志相关方法
  async getAuditLogs(): Promise<AuditLog[]> {
    return this.auditLogStorage.getItems();
  }

  // 数据验证方法 - 确保数据一致性
  async validateAllData(): Promise<{ isValid: boolean; errors: string[] }> {
    const errors: string[] = [];
    
    try {
      // 只加载必要的数据，避免任何可能的错误
      const classes = await this.getClasses();
      const students = await this.getStudents();
      const dormitories = await this.getDormitories();
      
      // 验证班级学生数量
      for (const cls of classes) {
        const actualCount = students.filter(
          student => student.classId === cls.id && student.status === 'active'
        ).length;
        
        if (cls.studentCount !== actualCount) {
          errors.push(`班级 ${cls.name} (ID: ${cls.id}) 学生数量不一致: 存储 ${cls.studentCount}, 实际 ${actualCount}`);
        }
      }
      
      // 验证学生的班级存在性
      for (const student of students) {
        if (student.classId) {
          const classExists = classes.some(cls => cls.id === student.classId);
          if (!classExists) {
            errors.push(`学生 ${student.name} (ID: ${student.id}) 的班级不存在: ${student.classId}`);
          }
        }
      }
      
      // 验证学生的宿舍存在性和性别匹配
      for (const student of students) {
        if (student.dormitoryId) {
          const dormExists = dormitories.some(dorm => dorm.id === student.dormitoryId);
          if (!dormExists) {
            errors.push(`学生 ${student.name} (ID: ${student.id}) 的宿舍不存在: ${student.dormitoryId}`);
          } else {
            const dormitory = dormitories.find(dorm => dorm.id === student.dormitoryId);
            if (dormitory && dormitory.type !== student.gender) {
              errors.push(`学生 ${student.name} (ID: ${student.id}) 的性别与宿舍类型不匹配: 学生性别 ${student.gender}, 宿舍类型 ${dormitory.type}`);
            }
          }
        }
      }
      
      // 验证宿舍入住人数
      for (const dorm of dormitories) {
        const actualOccupancy = students.filter(
          student => student.dormitoryId === dorm.id && student.status === 'active'
        ).length;
        
        if (dorm.currentOccupancy !== actualOccupancy) {
          errors.push(`宿舍 ${dorm.building}-${dorm.roomNumber} (ID: ${dorm.id}) 入住人数不一致: 存储 ${dorm.currentOccupancy}, 实际 ${actualOccupancy}`);
        }
        
        // 验证宿舍学生列表
        const actualStudentIds = students
          .filter(student => student.dormitoryId === dorm.id && student.status === 'active')
          .map(student => student.id);
        
        const storedStudentIds = dorm.students || [];
        const hasMismatch = 
          storedStudentIds.length !== actualStudentIds.length ||
          !actualStudentIds.every(id => storedStudentIds.includes(id)) ||
          !storedStudentIds.every(id => actualStudentIds.includes(id));
          
        if (hasMismatch) {
          errors.push(`宿舍 ${dorm.building}-${dorm.roomNumber} (ID: ${dorm.id}) 学生列表不一致`);
        }
      }
      
    } catch (error) {
      console.error('数据验证过程中发生错误:', error);
      errors.push(`数据验证过程中发生错误: ${error instanceof Error ? error.message : String(error)}`);
    }
    
    return {
      isValid: errors.length === 0,
      errors
    };
  }

  // 修复所有数据一致性问题
  async fixAllDataInconsistencies(): Promise<void> {
    const classes = await this.getClassStorage();
    
    // 修复所有班级的学生数量
    for (const cls of classes) {
      await this.updateClassStudentCount(cls.id);
    }
    
    // 修复所有宿舍的入住人数
    const dormitories = await this.getDormitories();
    for (const dorm of dormitories) {
      await this.updateDormitoryOccupancy(dorm.id);
    }
    
    console.log('数据一致性问题修复完成');
  }

  // 获取班级存储实例（仅供内部使用）
  private async getClassStorage(): Promise<Class[]> {
    return this.classStorage.getItems();
  }

  // 初始化默认数据（用于演示）
  async initializeDefaultData(): Promise<void> {
    // 检查是否已有数据
    const existingClasses = await this.getClasses();
    if (existingClasses.length > 0) {
      return; // 已有数据，不重复初始化
    }
    
    // 创建默认班级
    const class1 = await this.createClass({
      name: '高三1班',
      gradeLevel: '高三',
      headTeacherId: '',
      studentCount: 0,
      description: '高三年级第一班'
    });
    
    const class2 = await this.createClass({
      name: '高三2班',
      gradeLevel: '高三',
      headTeacherId: '',
      studentCount: 0,
      description: '高三年级第二班'
    });
    
    // 创建默认教师
    const teacher1 = await this.createTeacher({
      name: '张老师',
      subject: '语文',
      email: 'zhang@example.com',
      phone: '13800138001',
      status: 'active'
    });
    
    // 更新班级的班主任
    await this.updateClass(class1.id, { headTeacherId: teacher1.id });
    
    // 创建默认学生
    await this.createStudent({
      name: '李小明',
      classId: class1.id,
      studentId: '2024001',
      gender: 'male',
      dateOfBirth: '2006-01-15',
      contactNumber: '13900139001',
      status: 'active'
    });
    
    await this.createStudent({
      name: '王小红',
      classId: class1.id,
      studentId: '2024002',
      gender: 'female',
      dateOfBirth: '2006-03-20',
      contactNumber: '13900139002',
      status: 'active'
    });
    
    await this.createStudent({
      name: '刘小华',
      classId: class2.id,
      studentId: '2024003',
      gender: 'male',
      dateOfBirth: '2006-05-10',
      contactNumber: '13900139003',
      status: 'active'
    });
    
    await this.createStudent({
      name: '陈小梅',
      classId: class2.id,
      studentId: '2024004',
      gender: 'female',
      dateOfBirth: '2006-07-25',
      contactNumber: '13900139004',
      status: 'active'
    });
    
    await this.createStudent({
      name: '赵小刚',
      classId: class2.id,
      studentId: '2024005',
      gender: 'male',
      dateOfBirth: '2006-09-05',
      contactNumber: '13900139005',
      status: 'active'
    });
    
    console.log('默认数据初始化完成');
  }
}

// 导出数据服务单例实例
export const dataService = new DataService();

// 立即初始化数据
dataService.initData().then(() => {
  console.log('数据服务初始化完成');
}).catch(error => {
  console.error('数据服务初始化失败:', error);
});

// 导出类型
export * from './models';